﻿//-----------------------------------------------------------------------
// <copyright file="Configuration.aspx.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation.
// All rights reserved.
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
// </copyright>
// <author>Medha</author>
// <date>16-May-2011</date>
//-----------------------------------------------------------------------

namespace SmartTag.Layouts
{
    using System;
    using System.Security.Permissions;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Microsoft.SharePoint.ApplicationPages;
    using Microsoft.SharePoint.Utilities;
    using SmartTag.Common.Utility;
    using SmartTag.Configuration;

    /// <summary>
    /// Configuration Entity
    /// </summary>
    public partial class Configuration : ListPageBase
    {
        /// <summary>
        /// Document Library Id
        /// </summary>
        private string listId;

        /// <summary>
        /// Represents the method that handles the Init event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
        [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
        protected override void OnInit(EventArgs e)
        {
            this.EnsureChildControls();
            base.OnInit(e);
        }

        /// <summary>
        /// Creates the child controls on the <see cref="T:Microsoft.SharePoint.WebControls.UnsecuredLayoutsPageBase"/>.
        /// </summary>
        [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
        protected override void CreateChildControls()
        {
            this.btnOk.Click += new EventHandler(this.BtnOk_Click);
            this.btnCancel.Click += new EventHandler(this.BtnCancel_Click);
            this.btnClearConfiguration.Click += new EventHandler(this.BtnClearConfiguration_Click);

            // Initialize Page
            this.Initialize();

            base.CreateChildControls();
        }

        /// <summary>
        /// Handles the Click event of the BtnClearConfiguration control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void BtnClearConfiguration_Click(object sender, EventArgs e)
        {
            ConfigurationHelper.ClearConfiguration(this.List);
            this.RefreshUI();
        }

        /// <summary>
        /// Handles the Click event of the BtnOk control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void BtnOk_Click(object sender, EventArgs e)
        {
            DocumentLibraryConfiguration config = ConfigurationHelper.LoadConfiguration(this.List);
            config.SmartTagEnabled = this.rbYes.Checked;
            ConfigurationHelper.SaveConfiguration(this.List, config);
            SPUtility.Redirect(SPHttpUtility.UrlPathEncode(string.Format("listedit.aspx?List={0}", this.listId), true), SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current);
        }

        /// <summary>
        /// Handles the Click event of the BtnCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void BtnCancel_Click(object sender, EventArgs e)
        {
            SPUtility.Redirect(SPHttpUtility.UrlPathEncode(string.Format("listedit.aspx?List={0}", this.listId), true), SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current);
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        private void Initialize()
        {
            // Get the list id
            this.listId = "{" + this.List.ID.ToString() + "}";
            /* Fill the column information and set other UI values */
            this.RefreshUI();
        }

        /// <summary>
        /// Refreshes the UI.
        /// </summary>
        private void RefreshUI()
        {
            try
            {
                DocumentLibraryConfiguration config = ConfigurationHelper.LoadConfiguration(this.List);

                this.lnkAddColumn.PostBackUrl = SPHttpUtility.UrlPathEncode(string.Format("AddColumn.aspx?List={0}", this.listId), true);
                this.lnkAddMultipleColumns.PostBackUrl = SPHttpUtility.UrlPathEncode(string.Format("AddMultipleColumns.aspx?List={0}", this.listId), true);

                if (config != null)
                {
                    this.rbYes.Checked = config.SmartTagEnabled;
                    this.rbNo.Checked = !config.SmartTagEnabled;

                    // Delete all rows except header
                    TableRow header = this.tblColumns.Rows[0];
                    this.tblColumns.Rows.Clear();
                    this.tblColumns.Rows.Add(header);

                    foreach (ColumnConfiguration columnConfig in config.ColumnConfiguration)
                    {
                        using (TableRow row = new TableRow())
                        {
                            using (TableCell cell = new TableCell())
                            {
                                cell.CssClass = "ms-vb2";

                                // Create link button to edit column
                                using (LinkButton lnkButton = new LinkButton())
                                {
                                    lnkButton.Text = columnConfig.ColumnName;
                                    lnkButton.PostBackUrl = SPHttpUtility.UrlPathEncode(string.Format("EditColumn.aspx?List={0}&Field={1}", this.listId, columnConfig.ColumnId), true);
                                    cell.Controls.Add(lnkButton);
                                }

                                row.Cells.Add(cell);
                            }

                            using (TableCell cell = new TableCell())
                            {
                                cell.CssClass = "ms-vb2";
                                cell.Controls.Add(new LiteralControl(columnConfig.WordsToScan.ToString()));
                                row.Cells.Add(cell);
                            }

                            using (TableCell cell = new TableCell())
                            {
                                cell.CssClass = "ms-vb2";
                                cell.ColumnSpan = 2;
                                cell.Controls.Add(new LiteralControl(columnConfig.Relevance.ToString()));
                                row.Cells.Add(cell);
                            }

                            /* Add row */
                            this.tblColumns.Rows.Add(row);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error occured in RefreshUI", (int)TraceLogEventId.RefreshUI);
            }
        }
    }
}
